package com.huawei.bitfun.visitors;

import com.huawei.bitfun.OptimizeManager;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;

public class OptVisitor extends PsiElementVisitor {
    private final ProblemsHolder holder;
    private final String group;

    public OptVisitor(ProblemsHolder holder, String group) {
        this.holder = holder;
        this.group = group;
    }

    @Override
    public void visitFile(@NotNull PsiFile file) {
        super.visitFile(file);
        var filePath = file.getVirtualFile().getCanonicalPath();
        if (!OptimizeManager.getInstance().hasOptimizeFile(filePath)) {
            return;
        }
        var documents = OptimizeManager.getInstance().getDocumentBeans(filePath)
                .stream().filter(document -> group.equalsIgnoreCase(document.getPass()))
                .toList();
        if (documents.isEmpty()) {
            return;
        }
        for (var document : documents) {
            var element = VisitorUtils.findElementAtPosition(file, document.getLine(), document.getColumn());
            if (element == null) {
                continue;
            }
            holder.registerProblem(element, document.getName());
        }
    }
}